const express = require('express');
const router = express.Router();
const mysql = require('mysql2');
const { db } = require('../config');
const pool = mysql.createPool(db);

// 用户登录接口
router.post('/login', (req, res) => {
  const { username, password } = req.body;
  pool.query(
    'SELECT * FROM user WHERE username = ? AND password = ?',
    [username, password],
    (err, results) => {
      if (err) return res.status(500).json({ code: 1, message: '数据库错误' });
      if (results.length > 0) {
        res.json({ code: 0, message: '登录成功', user: results[0] });
      } else {
        res.json({ code: 1, message: '用户名或密码错误' });
      }
    }
  );
});

// 用户注册接口
router.post('/register', (req, res) => {
  const { username, password } = req.body;
  
  // 验证输入
  if (!username || !password) {
    return res.status(400).json({ code: 1, message: '用户名和密码不能为空' });
  }
  
  if (username.length < 3) {
    return res.status(400).json({ code: 1, message: '用户名至少3个字符' });
  }
  
  if (password.length < 6) {
    return res.status(400).json({ code: 1, message: '密码至少6个字符' });
  }
  
  // 检查用户名是否已存在
  pool.query(
    'SELECT * FROM user WHERE username = ?',
    [username],
    (err, results) => {
      if (err) return res.status(500).json({ code: 1, message: '数据库错误' });
      
      if (results.length > 0) {
        return res.json({ code: 1, message: '用户名已存在' });
      }
      
      // 创建新用户
      pool.query(
        'INSERT INTO user (username, password) VALUES (?, ?)',
        [username, password],
        (err2, result) => {
          if (err2) return res.status(500).json({ code: 1, message: '注册失败' });
          
          res.json({ 
            code: 0, 
            message: '注册成功', 
            user: { id: result.insertId, username: username }
          });
        }
      );
    }
  );
});

module.exports = router; 